package jnpf.service.impl;

import cn.hutool.core.util.StrUtil;
import jnpf.base.ActionResult;
import jnpf.base.service.BillRuleService;
import jnpf.base.service.impl.BillRuleServiceImpl;
import jnpf.entity.*;
import jnpf.mapper.EntityMapper;
import jnpf.model.template.TagVO;
import jnpf.model.template.relationVO;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.entity.*;

import cn.hutool.core.util.ObjectUtil;
import jnpf.util.GeneraterSwapUtil;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;

import jnpf.model.QueryModel;

import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import jnpf.util.UserProvider;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import jnpf.util.*;

import java.util.*;

import jnpf.base.UserInfo;

/**
 * entity
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-04-10
 */
@Service
public class EntityServiceImpl extends ServiceImpl<EntityMapper, EntityEntity> implements EntityService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private EntityCategoryService entityCategoryService;
    @Autowired
    private EntityAttributeService entityAttributeService;

    @Autowired
    private TagMangeService tagMangeService;
    @Autowired
    private RelationMangeService relationMangeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private RelationService relationService;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private TemplateCategoryService templateCategoryService;

    @Autowired
    private TemplateAttributeService templateAttributeService;

    @Autowired
    private ZmnService zmnService;

    @Autowired
    private BillRuleService billRuleService;


    @Override
    public List<EntityEntity> getList(EntityPagination entityPagination) {
        return getTypeList(entityPagination, entityPagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<EntityEntity> getTypeList(EntityPagination entityPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? EntityConstant.getAppColumnData() : EntityConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int entityNum = 0;
        QueryWrapper<EntityEntity> entityQueryWrapper = new QueryWrapper<>();
        int entityAttributeNum = 0;
        QueryWrapper<EntityAttributeEntity> entityAttributeQueryWrapper = new QueryWrapper<>();
        int entityCategoryNum = 0;
        QueryWrapper<EntityCategoryEntity> entityCategoryQueryWrapper = new QueryWrapper<>();
        long entityAttributecount = entityAttributeService.count();
        long entityCategorycount = entityCategoryService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(entityPagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = entityPagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<EntityEntity> entitySuperWrapper = new QueryWrapper<>();
            entitySuperWrapper = generaterSwapUtil.getCondition(new QueryModel(entitySuperWrapper, EntityEntity.class, queryJson, "0"));
            int entityNum1 = entitySuperWrapper.getExpression().getNormal().size();
            if (entityNum1 > 0) {
                List<String> entityList = this.list(entitySuperWrapper).stream().map(EntityEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(entityList);
                intersectionSuperList.add(entityList);
                superNum++;
            }
            String entityAttributeTable = "entity_attribute";
            boolean entityAttributeHasSql = queryJson.contains(entityAttributeTable);
            List<String> entityAttributeList = generaterSwapUtil.selectIdsByChildCondition(EntityConstant.getTableList(), entityAttributeTable, queryJson, null);
            if (entityAttributeHasSql) {
                allSuperList.addAll(entityAttributeList);
                intersectionSuperList.add(entityAttributeList);
                superNum++;
            }
            String entityCategoryTable = "entity_category";
            boolean entityCategoryHasSql = queryJson.contains(entityCategoryTable);
            List<String> entityCategoryList = generaterSwapUtil.selectIdsByChildCondition(EntityConstant.getTableList(), entityCategoryTable, queryJson, null);
            if (entityCategoryHasSql) {
                allSuperList.addAll(entityCategoryList);
                intersectionSuperList.add(entityCategoryList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<EntityEntity> entitySuperWrapper = new QueryWrapper<>();
            entitySuperWrapper = generaterSwapUtil.getCondition(new QueryModel(entitySuperWrapper, EntityEntity.class, ruleJson, "0"));
            int entityNum1 = entitySuperWrapper.getExpression().getNormal().size();
            if (entityNum1 > 0) {
                List<String> entityList = this.list(entitySuperWrapper).stream().map(EntityEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(entityList);
                intersectionRuleList.add(entityList);
                ruleNum++;
            }
            String entityAttributeTable = "entity_attribute";
            boolean entityAttributeHasSql = ruleJson.contains(entityAttributeTable);
            List<String> entityAttributeList = generaterSwapUtil.selectIdsByChildCondition(EntityConstant.getTableList(), entityAttributeTable, ruleJson, null);
            if (entityAttributeHasSql) {
                allRuleList.addAll(entityAttributeList);
                intersectionRuleList.add(entityAttributeList);
                ruleNum++;
            }
            String entityCategoryTable = "entity_category";
            boolean entityCategoryHasSql = ruleJson.contains(entityCategoryTable);
            List<String> entityCategoryList = generaterSwapUtil.selectIdsByChildCondition(EntityConstant.getTableList(), entityCategoryTable, ruleJson, null);
            if (entityCategoryHasSql) {
                allRuleList.addAll(entityCategoryList);
                intersectionRuleList.add(entityCategoryList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object entityObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityQueryWrapper, EntityEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityObj)) {
                    return new ArrayList<>();
                } else {
                    entityQueryWrapper = (QueryWrapper<EntityEntity>) entityObj;
                    if (entityQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityNum++;
                    }
                }
                Object entityAttributeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityAttributeQueryWrapper, EntityAttributeEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityAttributeObj)) {
                    return new ArrayList<>();
                } else {
                    entityAttributeQueryWrapper = (QueryWrapper<EntityAttributeEntity>) entityAttributeObj;
                    if (entityAttributeQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityAttributeNum++;
                    }
                }
                Object entityCategoryObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityCategoryQueryWrapper, EntityCategoryEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityCategoryObj)) {
                    return new ArrayList<>();
                } else {
                    entityCategoryQueryWrapper = (QueryWrapper<EntityCategoryEntity>) entityCategoryObj;
                    if (entityCategoryQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityCategoryNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object entityObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityQueryWrapper, EntityEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityObj)) {
                    return new ArrayList<>();
                } else {
                    entityQueryWrapper = (QueryWrapper<EntityEntity>) entityObj;
                    if (entityQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityNum++;
                    }
                }


                Object entityAttributeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityAttributeQueryWrapper, EntityAttributeEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityAttributeObj)) {
                    return new ArrayList<>();
                } else {
                    entityAttributeQueryWrapper = (QueryWrapper<EntityAttributeEntity>) entityAttributeObj;
                    if (entityAttributeQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityAttributeNum++;
                    }
                }


                Object entityCategoryObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(entityCategoryQueryWrapper, EntityCategoryEntity.class, entityPagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(entityCategoryObj)) {
                    return new ArrayList<>();
                } else {
                    entityCategoryQueryWrapper = (QueryWrapper<EntityCategoryEntity>) entityCategoryObj;
                    if (entityCategoryQueryWrapper.getExpression().getNormal().size() > 0) {
                        entityCategoryNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(entityPagination.getName())) {
                entityNum++;

                String value = entityPagination.getName() instanceof List ? JsonUtil.getObjectToString(entityPagination.getName()) : String.valueOf(entityPagination.getName());
                entityQueryWrapper.lambda().like(EntityEntity::getName, value);

            }

            if (ObjectUtil.isNotEmpty(entityPagination.getBelongUserId())) {
                entityNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] belongUserId = JsonUtil.getJsonToBean(entityPagination.getBelongUserId(), String[][].class);
                    for (int i = 0; i < belongUserId.length; i++) {
                        if (belongUserId[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(belongUserId[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> belongUserId = JsonUtil.getJsonToList(entityPagination.getBelongUserId(), String.class);
                        if (belongUserId.size() > 0) {
                            idList.addAll(belongUserId);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(entityPagination.getBelongUserId()));
                    }
                }
                entityQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(EntityEntity::getBelongUserId, tt).or();
                    });
                });

            }

//            if (ObjectUtil.isNotEmpty(entityPagination.getDataLevel())) {
//                entityNum++;
//
//                List<String> idList = new ArrayList<>();
//                try {
//                    String[][] dataLevel = JsonUtil.getJsonToBean(entityPagination.getDataLevel(), String[][].class);
//                    for (int i = 0; i < dataLevel.length; i++) {
//                        if (dataLevel[i].length > 0) {
//                            idList.add(JsonUtil.getObjectToString(Arrays.asList(dataLevel[i])));
//                        }
//                    }
//                } catch (Exception e1) {
//                    try {
//                        List<String> dataLevel = JsonUtil.getJsonToList(entityPagination.getDataLevel(), String.class);
//                        if (dataLevel.size() > 0) {
//                            idList.addAll(dataLevel);
//                        }
//                    } catch (Exception e2) {
//                        idList.add(String.valueOf(entityPagination.getDataLevel()));
//                    }
//                }
//                entityQueryWrapper.lambda().and(t -> {
//                    idList.forEach(tt -> {
//                        t.like(EntityEntity::getDataLevel, tt).or();
//                    });
//                });
//
//            }

        }
        if (entityAttributeNum > 0) {
            List<String> entityAttributeIdList = entityAttributeService.list(entityAttributeQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getEntityId())).map(t -> t.getEntityId()).collect(Collectors.toList());
            long count = entityAttributeService.count();
            if (count > 0) {
                intersectionList.add(entityAttributeIdList);
            }
            AllIdList.addAll(entityAttributeIdList);
        }
        total += entityAttributeNum;
        if (entityCategoryNum > 0) {
            List<String> entityCategoryIdList = entityCategoryService.list(entityCategoryQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getEntityId())).map(t -> t.getEntityId()).collect(Collectors.toList());
            long count = entityCategoryService.count();
            if (count > 0) {
                intersectionList.add(entityCategoryIdList);
            }
            AllIdList.addAll(entityCategoryIdList);
        }
        total += entityCategoryNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            entityQueryWrapper.lambda().in(EntityEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            entityQueryWrapper.lambda().and(t -> t.in(EntityEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            entityQueryWrapper.lambda().and(t -> t.in(EntityEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(entityPagination.getSidx())) {
            entityQueryWrapper.lambda().orderByDesc(EntityEntity::getId);
        } else {
            try {
                String sidx = entityPagination.getSidx();
                String[] strs = sidx.split("_name");
                EntityEntity entityEntity = new EntityEntity();
                Field declaredField = entityEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                entityQueryWrapper = "asc".equals(entityPagination.getSort().toLowerCase()) ? entityQueryWrapper.orderByAsc(value) : entityQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<EntityEntity> page = new Page<>(entityPagination.getCurrentPage(), entityPagination.getPageSize());
                IPage<EntityEntity> userIPage = this.page(page, entityQueryWrapper);
                return entityPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<EntityEntity> list = new ArrayList();
                return entityPagination.setData(list, list.size());
            }
        } else {
            return this.list(entityQueryWrapper);
        }
    }

    @Override
    public EntityEntity getInfo(String id) {
        QueryWrapper<EntityEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(EntityEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, EntityEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(EntityEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * EntityCategory子表方法
     */
    @Override
    public List<EntityCategoryEntity> getEntityCategoryList(String id, EntityPagination entityPagination) {
        Map<String, Object> newtabMap = EntityConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "entityCategory";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<EntityCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = entityCategoryService.getChild(entityPagination, queryWrapper);
        queryWrapper.lambda().eq(EntityCategoryEntity::getEntityId, id);
        generaterSwapUtil.wrapperHandle(EntityConstant.getColumnData(), EntityConstant.getAppColumnData(), queryWrapper, EntityCategoryEntity.class, "sub", tableName);
        return entityCategoryService.list(queryWrapper);
    }

    /**
     * EntityCategory子表方法
     */
    @Override
    public List<EntityCategoryEntity> getEntityCategoryList(String id) {
        QueryWrapper<EntityCategoryEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityCategoryEntity::getEntityId, id);
        return entityCategoryService.list(queryWrapper);
    }

    /**
     * EntityAttribute子表方法
     */
    @Override
    public List<EntityAttributeEntity> getEntityAttributeList(String id, EntityPagination entityPagination) {
        Map<String, Object> newtabMap = EntityConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "entityAttribute";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<EntityAttributeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = entityAttributeService.getChild(entityPagination, queryWrapper);
        queryWrapper.lambda().eq(EntityAttributeEntity::getEntityId, id);
        generaterSwapUtil.wrapperHandle(EntityConstant.getColumnData(), EntityConstant.getAppColumnData(), queryWrapper, EntityAttributeEntity.class, "sub", tableName);
        return entityAttributeService.list(queryWrapper);
    }

    /**
     * EntityAttribute子表方法
     */
    @Override
    public List<EntityAttributeEntity> getEntityAttributeList(String id) {
        QueryWrapper<EntityAttributeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EntityAttributeEntity::getEntityId, id);
        return entityAttributeService.list(queryWrapper);
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(EntityEntity form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getName())) {
            return "实体名称不能为空";
        }
        //子表字段验证
        if (form.getEntityCategoryList() != null) {
            for (EntityCategoryEntity t : form.getEntityCategoryList()) {
                if (StringUtil.isNotEmpty(t.getCategory())) {
                    t.setCategory(t.getCategory().trim());
                } else {
                    return "分类-分类名称不能为空";
                }
            }
        }
        for (EntityCategoryEntity entityCategoryEntity : form.getEntityCategoryList()) {
            for (EntityAttributeEntity entityAttributeEntity : entityCategoryEntity.getEntityAttributeList()) {
                if (StrUtil.isEmpty(entityAttributeEntity.getAttrName())) {
                    return "属性和值-属性名称不能为空";
                }
            }
        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public String saveOrUpdate(EntityEntity entity, String id, boolean isSave) throws Exception {
        UserInfo userInfo = userProvider.get();
        Boolean isUpdate = entity.getIsUpdate();

        //有id，没机构变化，正常更新
        if (!isUpdate) {
            // 设置主表信息
            if (id == null) {
                entity.setId(RandomUtil.uuId());
            }

            entity.setCreateUserId(userInfo.getUserId());
            entity.setCreateTime(DateUtil.getNowDate());
            this.saveOrUpdate(entity);

            // 处理TemplateCategory子表数据(1对多)
            if (!isSave) {
                QueryWrapper<EntityCategoryEntity> categoryQueryWrapper = new QueryWrapper<>();
                categoryQueryWrapper.lambda().eq(EntityCategoryEntity::getEntityId, entity.getId());
                entityCategoryService.remove(categoryQueryWrapper);
            }
            if (entity.getEntityCategoryList() != null && !entity.getEntityCategoryList().isEmpty()) {
                // 保存分类数据
                List<EntityCategoryEntity> categories = entity.getEntityCategoryList().stream().peek(category -> {
                    category.setId(RandomUtil.uuId());
                    category.setEntityId(entity.getId());
                    category.setCreateUserId(userInfo.getUserId());
                    category.setCreateTime(DateUtil.getNowDate());
                }).collect(Collectors.toList());
                entityCategoryService.saveBatch(categories);


                // 属性值
                // 先删除旧属性
                if (!isSave) {
                    QueryWrapper<EntityAttributeEntity> attributeQueryWrapper = new QueryWrapper<>();
                    attributeQueryWrapper.lambda().eq(EntityAttributeEntity::getEntityId, entity.getId());
                    entityAttributeService.remove(attributeQueryWrapper);
                }

                //处理每个分类下的属性数据(多对多)
                for (EntityCategoryEntity category : categories) {
                    if (category.getEntityAttributeList() != null && !category.getEntityAttributeList().isEmpty()) {

                        // 保存新属性
                        List<EntityAttributeEntity> attributes = category.getEntityAttributeList().stream().peek(attribute -> {
                            attribute.setId(RandomUtil.uuId());
                            attribute.setEntityId(entity.getId());
                            attribute.setCategoryId(category.getId());
                            attribute.setCreateUserId(userInfo.getUserId());
                            attribute.setCreateTime(DateUtil.getNowDate());
                        }).collect(Collectors.toList());
                        entityAttributeService.saveBatch(attributes);
                    }
                }
            }
        }
        //更新，若没有id,则先创建模板，然后根据模板实体，若存在id，则先创建新版本模板，然后再新版本模板下创建实体
        else {
            if (StringUtil.isEmpty(id)) {
                // 1. 创建模板主表
                TemplateEntity template = new TemplateEntity();
                template.setName(entity.getName());
                template.setIsMain("1");
                template.setCreateUserId(userInfo.getUserId());
                template.setCreateTime(new Date());
                templateService.saveOrUpdate(template, null, true);

                // 2. 创建模板分类和属性
                if (entity.getEntityCategoryList() != null && !entity.getEntityCategoryList().isEmpty()) {
                    List<TemplateCategoryEntity> templateCategories = new ArrayList<>();
                    List<TemplateAttributeEntity> templateAttributes = new ArrayList<>();

                    for (EntityCategoryEntity entityCategory : entity.getEntityCategoryList()) {
                        // 创建模板分类
                        TemplateCategoryEntity templateCategory = new TemplateCategoryEntity();
                        templateCategory.setId(RandomUtil.uuId());
                        templateCategory.setTemplateId(template.getId());
                        templateCategory.setCategory(entityCategory.getCategory());
                        templateCategory.setCreateUserId(userInfo.getUserId());
                        templateCategory.setCreateTime(new Date());
                        templateCategories.add(templateCategory);

                        // 创建模板属性
                        if (entityCategory.getEntityAttributeList() != null) {
                            for (EntityAttributeEntity entityAttribute : entityCategory.getEntityAttributeList()) {
                                TemplateAttributeEntity templateAttribute = new TemplateAttributeEntity();
                                templateAttribute.setId(RandomUtil.uuId());
                                templateAttribute.setTemplateId(template.getId());
                                templateAttribute.setCategoryId(templateCategory.getId());
                                templateAttribute.setAttrName(entityAttribute.getAttrName());
                                templateAttribute.setAttrType(entityAttribute.getAttrType());
                                templateAttribute.setCreateUserId(userInfo.getUserId());
                                templateAttribute.setCreateTime(new Date());
                                templateAttributes.add(templateAttribute);
                            }
                        }
                    }

                    // 批量保存模板分类和属性
                    templateCategoryService.saveBatch(templateCategories);
                    if (!templateAttributes.isEmpty()) {
                        templateAttributeService.saveBatch(templateAttributes);
                    }
                }

                // 4. 保存实体信息
                entity.setId(RandomUtil.uuId());
                entity.setTemplateId(template.getId());
                entity.setCreateUserId(userInfo.getUserId());
                entity.setCreateTime(new Date());
                String doEntityFLow = billRuleService.getBillNumber("doEntityFLow", false);
                entity.setNumber(doEntityFLow);
                this.save(entity);

                // 5. 保存实体分类和属性
                if (entity.getEntityCategoryList() != null && !entity.getEntityCategoryList().isEmpty()) {
                    List<EntityCategoryEntity> categories = entity.getEntityCategoryList().stream().peek(category -> {
                        category.setId(RandomUtil.uuId());
                        category.setEntityId(entity.getId());
                        category.setCreateUserId(userInfo.getUserId());
                        category.setCreateTime(new Date());
                    }).collect(Collectors.toList());
                    entityCategoryService.saveBatch(categories);

                    for (EntityCategoryEntity category : categories) {
                        if (category.getEntityAttributeList() != null && !category.getEntityAttributeList().isEmpty()) {
                            List<EntityAttributeEntity> attributes = category.getEntityAttributeList().stream().peek(attribute -> {
                                attribute.setId(RandomUtil.uuId());
                                attribute.setEntityId(entity.getId());
                                attribute.setCategoryId(category.getId());
                                attribute.setCreateUserId(userInfo.getUserId());
                                attribute.setCreateTime(new Date());
                            }).collect(Collectors.toList());
                            entityAttributeService.saveBatch(attributes);
                        }
                    }
                }
            }

         else{
                // 1. 查询原有实体和模板信息
                EntityEntity oldEntity = this.getById(id);
                if (oldEntity == null) {
                    return "找不到要更新的实体";
                }

                // 2. 查询原有模板信息
                TemplateEntity oldTemplate = templateService.getInfo(oldEntity.getTemplateId());
                if (oldTemplate == null) {
                    return "找不到关联的模板";
                }

                // 3. 创建新版本模板主表
                TemplateEntity newTemplate = new TemplateEntity();
                newTemplate.setName(oldTemplate.getName()); // 使用原模板名称
                newTemplate.setIsMain("2");
                newTemplate.setType("3");
                newTemplate.setIsDefault(2);
                newTemplate.setFirstUpdateId(oldTemplate.getFirstUpdateId());
                newTemplate.setVersion(oldTemplate.getVersion() + 1);
                newTemplate.setLastUpdateId(oldTemplate.getId());
                newTemplate.setCreateUserId(userInfo.getUserId());
                newTemplate.setCreateTime(new Date());
                templateService.create(newTemplate);

                // 4. 复制模板分类和属性
                QueryWrapper<TemplateCategoryEntity> categoryQueryWrapper = new QueryWrapper<>();
                categoryQueryWrapper.lambda().eq(TemplateCategoryEntity::getTemplateId, oldTemplate.getId());
                List<TemplateCategoryEntity> oldCategories = templateCategoryService.list(categoryQueryWrapper);

                if (oldCategories != null && !oldCategories.isEmpty()) {
                    List<TemplateCategoryEntity> newCategories = new ArrayList<>();
                    List<TemplateAttributeEntity> newAttributes = new ArrayList<>();

                    for (TemplateCategoryEntity oldCategory : oldCategories) {
                        // 创建新模板分类
                        TemplateCategoryEntity newCategory = new TemplateCategoryEntity();
                        newCategory.setId(RandomUtil.uuId());
                        newCategory.setTemplateId(newTemplate.getId());
                        newCategory.setCategory(oldCategory.getCategory());
                        newCategory.setCreateUserId(userInfo.getUserId());
                        newCategory.setCreateTime(new Date());
                        newCategories.add(newCategory);

                        // 复制模板属性
                        QueryWrapper<TemplateAttributeEntity> attributeQueryWrapper = new QueryWrapper<>();
                        attributeQueryWrapper.lambda().eq(TemplateAttributeEntity::getCategoryId, oldCategory.getId());
                        List<TemplateAttributeEntity> oldAttributes = templateAttributeService.list(attributeQueryWrapper);

                        if (oldAttributes != null) {
                            for (TemplateAttributeEntity oldAttribute : oldAttributes) {
                                TemplateAttributeEntity newAttribute = new TemplateAttributeEntity();
                                newAttribute.setId(RandomUtil.uuId());
                                newAttribute.setTemplateId(newTemplate.getId());
                                newAttribute.setCategoryId(newCategory.getId());
                                newAttribute.setAttrName(oldAttribute.getAttrName());
                                newAttribute.setAttrType(oldAttribute.getAttrType());
                                newAttribute.setCreateUserId(userInfo.getUserId());
                                newAttribute.setCreateTime(new Date());
                                newAttributes.add(newAttribute);
                            }
                        }
                    }

                    // 批量保存新模板分类和属性
                    templateCategoryService.saveBatch(newCategories);
                    if (!newAttributes.isEmpty()) {
                        templateAttributeService.saveBatch(newAttributes);
                    }
                }

                // 5. 在新版本模板下创建实体
                ActionResult<String> result = zmnService.createEntity(newTemplate.getId(), 1);
                if (result.getCode() != 200) {
                    throw new Exception("在新版本模板下创建实体失败: " + result.getMsg());
                }


                // 7. 处理子表数据（先删除旧数据再保存新数据）
                QueryWrapper<EntityCategoryEntity> categoryQueryWrappert = new QueryWrapper<>();
                categoryQueryWrappert.lambda().eq(EntityCategoryEntity::getEntityId, entity.getId());
                entityCategoryService.remove(categoryQueryWrappert);

                if (entity.getEntityCategoryList() != null && !entity.getEntityCategoryList().isEmpty()) {
                    List<EntityCategoryEntity> categories = entity.getEntityCategoryList().stream().peek(category -> {
                        category.setId(RandomUtil.uuId());
                        category.setEntityId(entity.getId());
                        category.setCreateUserId(userInfo.getUserId());
                        category.setCreateTime(new Date());
                    }).collect(Collectors.toList());
                    entityCategoryService.saveBatch(categories);

                    QueryWrapper<EntityAttributeEntity> attributeQueryWrapper = new QueryWrapper<>();
                    attributeQueryWrapper.lambda().eq(EntityAttributeEntity::getEntityId, entity.getId());
                    entityAttributeService.remove(attributeQueryWrapper);

                    for (EntityCategoryEntity category : categories) {
                        if (category.getEntityAttributeList() != null && !category.getEntityAttributeList().isEmpty()) {
                            List<EntityAttributeEntity> attributes = category.getEntityAttributeList().stream().peek(attribute -> {
                                attribute.setId(RandomUtil.uuId());
                                attribute.setEntityId(entity.getId());
                                attribute.setCategoryId(category.getId());
                                attribute.setCreateUserId(userInfo.getUserId());
                                attribute.setCreateTime(new Date());
                            }).collect(Collectors.toList());
                            entityAttributeService.saveBatch(attributes);
                        }
                    }
                }
            }
        }
        return "";
    }


    @Override
    @Transactional
    public void saveTagAndRelation(EntityEntity entity, String id, String isPre, String saveTagType) {
        // 处理标签关联信息
        if (entity.getTagList() != null) {
            // 1. 先删除该实体的所有标签关联信息
            QueryWrapper<TagMangeEntity> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.lambda().eq(TagMangeEntity::getEntityId, id);
            tagMangeService.remove(deleteWrapper);

            // 2. 插入新的标签关联信息
            for (TagVO tagVO : entity.getTagList()) {
                // 如果tagId不为空且是自定义标签(type=4)，则更新Tag表
                if (StrUtil.isNotEmpty(tagVO.getTagId()) && "4".equals(tagVO.getTagType())) {
                    TagEntity tag = new TagEntity();
                    tag.setId(tagVO.getTagId());
                    tag.setName(tagVO.getTagName());
                    tag.setTagType(tagVO.getTagType());
                    tag.setIsPre(isPre);
                    tagService.updateById(tag);
                }
                // 如果tagId为空，则先保存到Tag表
                else if (StrUtil.isEmpty(tagVO.getTagId())) {
                    TagEntity tag = new TagEntity();
                    tag.setId(RandomUtil.uuId());
                    tag.setName(tagVO.getTagName());
                    tag.setTagType(tagVO.getTagType());
                    tag.setIsPre(isPre);
                    tag.setCreateUserId(UserProvider.getLoginUserId());
                    tag.setCreateTime(new Date());
                    tagService.save(tag);
                    tagVO.setTagId(tag.getId());
                }

                TagMangeEntity tagMange = new TagMangeEntity();
                tagMange.setTagId(tagVO.getTagId());
                tagMange.setTagType(tagVO.getTagType());

                tagMange.setEntityId(entity.getId());

                tagMange.setTagType(saveTagType);
                tagMange.setCreateUserId(UserProvider.getLoginUserId());
                tagMange.setCreateTime(new Date());
                tagMange.setEnabled(1);

                tagMangeService.save(tagMange);
            }
        }

        // 处理关系关联信息
        if (entity.getRelationList() != null) {
            // 1. 先删除该实体的所有关系关联信息
            QueryWrapper<RelationMangeEntity> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.lambda().eq(RelationMangeEntity::getEntityId, id);
            relationMangeService.remove(deleteWrapper);

            // 2. 插入新的关系关联信息
            for (relationVO relationVO : entity.getRelationList()) {
                RelationMangeEntity relationInfo = new RelationMangeEntity();
                relationInfo.setRelationId(relationVO.getRelationId());

                relationInfo.setEntityId(entity.getId());

                relationInfo.setTargetEntityId(relationVO.getTargetEntityId());
                relationInfo.setTagId(relationVO.getTagId());
                relationInfo.setDirection(relationVO.getDirection());
                relationInfo.setCreateUserId(UserProvider.getLoginUserId());
                relationInfo.setCreateTime(new Date());

                relationMangeService.save(relationInfo);
            }
        }
    }
}

